/*
	后台-新闻控制器
*/
'use strict';
var moment		= require('moment');
var AV 				= require('leanengine');
var mdCommon	= require('../modules/common');

var avQuestion 		= AV.Object.extend("Question");

/**
 * 文章详情页面
 * 2016.05.03  by 胡斌
 */
exports.detailPage = function(req, res) {
	var user						= req.AV.user;
	var skip						= user.get("skip");
	var queryQuestion 	= new AV.Query(avQuestion);
	if(typeof(skip)=="undefined")skip=0;

	queryQuestion.doesNotExist("fromVideo");
	queryQuestion.notEqualTo("type","advert");
	queryQuestion.doesNotExist("validator");
	queryQuestion.ascending("createdAt");
	//queryQuestion.sizeEqualTo("validator",0);
	queryQuestion.skip(skip);
	queryQuestion.first().then(function(result) {
		//console.log(result);
		if(typeof(result)=="undefined")result=false;
		res.render('admin-news-detail.html',{
			user:req.AV.user,
			result:result,
			answers:result.get("answers"),
			moment:moment
		});
	},function(error) {
		mdCommon.sentErr(res,req,error);
	});
}

/**
 * 文章详情页面
 * 2016.05.03  by 胡斌
 */
exports.validPage = function(req, res) {
	var user						= req.AV.user;
	var queryQuestion 	= new AV.Query(avQuestion);

	queryQuestion.doesNotExist("fromVideo");
	queryQuestion.notEqualTo("type","advert");
	queryQuestion.exists("validator");
	queryQuestion.ascending("createdAt");
	queryQuestion.count().then(function(count) {
		var skip=mdCommon.randomIntArray(1,count);
		queryQuestion.skip(skip[0]);
		return queryQuestion.first();
	}).then(function(result) {
		//console.log(result);
		if(typeof(result)=="undefined")result=false;
		res.render('admin-news-detail.html',{
			user:req.AV.user,
			result:result,
			answers:result.get("answers"),
			moment:moment
		});
	},function(error) {
		mdCommon.sentErr(res,req,error);
	});
}

/**
 * 文章管理-保存
 * 2015.05.24  by 胡斌
 */
exports.doSave = function(req, res) {
	//console.log("doSave");
	var user					= req.AV.user;
	var answers				= [];
	var id						= req.body.id;
	var type					= req.body.type;
	var title					= req.body.title.trim();
	var rightAnswer		= req.body.answer;
	var wrongAnswer		= req.body.answers.split("||");
	var queryQuestion = new AV.Query(avQuestion);

	queryQuestion.equalTo("objectId",id);
	queryQuestion.first().then(function(Question) {
		var answersArr=Question.get("answers");
		for(var i=0;i<wrongAnswer.length;i++){
			var answer={};
			answer.a=false;
			answer.v=wrongAnswer[i];
			answers.push(answer);
		}
		var answer={};
		answer.a=true;
		answer.v=rightAnswer;
		answers.push(answer);

		Question.set("title",title);
		Question.set("answers",answers);
		Question.addUnique('validator',user.id);
		return Question.save();
	}).then(function(result) {
		user.addUnique(type,result.id);
		user.save();
		res.json({result:result});
	},function(error){
		console.dir(error);
		mdCommon.sentErr(res,req,error);
	});
}
